using System;
using System.Xml;
using DesignPatternDefinitions;

namespace CodeGenerators
{
	internal class VBProjectGenerator : DefaultProjectGenerator
	{
		private XmlDocument mDoc;
		private IProject mProject;
		
		public override string GenerateProjectFile(string directory, IProject project)
		{
			string projectRoot = base.GenerateProjectFile(directory,project);
			string fileName = projectRoot + "\\" + project.ProjectName + ".vbproj";
			string templatePath = System.Windows.Forms.Application.StartupPath + Constants.TEMPLATEPATH +"\\Template.vbproj";
			try
			{
				mProject = project;
				mDoc = new XmlDocument();
				mDoc.Load( templatePath );
				AddHeaderData();
				AddClasses();
				mDoc.Save( fileName );
			}
			catch(Exception e)
			{
				System.Windows.Forms.MessageBox.Show(""+e);
			}
			return projectRoot;
		}

		private void AddHeaderData()
		{
			XmlElement vbnode = mDoc.DocumentElement.SelectSingleNode("VisualBasic") as XmlElement;
			vbnode.Attributes["ProjectGuid"].Value = Guid.NewGuid().ToString("P");
			
			XmlElement settings = vbnode.SelectSingleNode("Build/Settings") as XmlElement;
			settings.Attributes["AssemblyName"].Value = mProject.ProjectName;
			settings.Attributes["RootNamespace"].Value = mProject.ProjectName;
			settings.Attributes["StartupObject"].Value = mProject.ProjectName + ".(None)";
		}
		private void AddClasses()
		{
			XmlElement files = mDoc.DocumentElement.SelectSingleNode("VisualBasic/Files/Include") as XmlElement;
			foreach( IProjectComponent component in mProject.Components )
			{
				foreach( IClass cls in component.Classes )
				{
					XmlElement elem = mDoc.CreateElement( "File" );
					XmlAttribute rpath = mDoc.CreateAttribute("RelPath");
					rpath.Value = component.ComponentName + "\\" + cls.ClassName + ".vb";
					XmlAttribute stype = mDoc.CreateAttribute("SubType");
					stype.Value = "Code";
					XmlAttribute action = mDoc.CreateAttribute("BuildAction");
					action.Value = "Compile";
					elem.Attributes.Append(rpath);
					elem.Attributes.Append(stype);
					elem.Attributes.Append(action);
					files.AppendChild( elem );
				}
			}
		}
	}
}
